package com.rjpacket.supernews.app.fragments;


import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.rjpacket.supernews.app.Constants;
import com.rjpacket.supernews.app.DuanziDetailActivity;
import com.rjpacket.supernews.app.R;
import com.rjpacket.supernews.app.adapter.DuanziAdapter;
import com.rjpacket.supernews.app.model.Duanzi;
import com.rjpacket.supernews.app.model.DuanziDetail;
import com.rjpacket.supernews.app.task.DuanziDetailTask;
import com.rjpacket.supernews.app.task.DuanziListTask;
import com.rjpacket.supernews.app.tasks.DetailTaskCallOnBack;
import com.rjpacket.supernews.app.tasks.TaskCallOnBack;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class DuanziFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2, AdapterView.OnItemClickListener, TaskCallOnBack, DetailTaskCallOnBack {

    private PullToRefreshListView refresh;
    private LinkedList<Duanzi> data;
    private int headerViewsCount;

    private DuanziAdapter adapter;

    public DuanziFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.mz_fragment_duanzi, container, false);

        //获得刷新控件
        refresh = (PullToRefreshListView) ret.findViewById(R.id.duanzi_pull_to_refresh_list_view);
        //设置两边都能刷新
        refresh.setMode(PullToRefreshBase.Mode.BOTH);

        //绑定监听器
        refresh.setOnRefreshListener(this);
        Resources res = getResources();
        Drawable drawable = res.getDrawable(R.drawable.light_loading_0);

        // 设置加载图标
        refresh.setLoadingDrawable(drawable);
        // 设置加载中的标题
        refresh.setRefreshingLabel("下拉可以刷新");
        // 设置“松开”提醒
        refresh.setReleaseLabel("松开即可刷新");

        //获得ListView
        ListView listView = refresh.getRefreshableView();
        //设置分割线
        listView.setDividerHeight(2);

        headerViewsCount = listView.getHeaderViewsCount();

        if (listView != null) {

            data = new LinkedList<Duanzi>();
            adapter = new DuanziAdapter(getActivity(), data);

            listView.setAdapter(adapter);
            //listView绑定点击事件, 点击进入段子详情
            listView.setOnItemClickListener(this);
        }

        String url = Constants.DUANZI_LIST_URL;

        DuanziListTask task = new DuanziListTask(this);
        task.execute(url);

        TextView time = (TextView) ret.findViewById(R.id.fragment_duanzi_time);
        TextView today = (TextView) ret.findViewById(R.id.fragment_duanzi_today);

        //最上方显示的时间  和  距离上次刷新的时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String currentTime = formatter.format(curDate);
        time.setText(currentTime);

        //TODO  处理右侧 显示今天 昨天 两天前

        return ret;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(getActivity(), DuanziDetailActivity.class);
        Duanzi news = data.get(position - headerViewsCount);
        intent.putExtra("news", news.getDuanziDetail());
        intent.putExtra("content", news.getContent());
        startActivity(intent);

    }

    /**
     * 数据刷新
     *
     * @param refreshView
     */
    /////////////////////////////////
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {

    }

    @Override
    public void callBack(Object object, String position) {
        if (object != null && object instanceof JSONObject) {
            String string = (String) object;

            JSONObject json = null;
            try {
                json = new JSONObject(string);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            DuanziDetail detail = new DuanziDetail();
            detail.parseJSON(json);
            Duanzi news = data.get(Integer.parseInt(position));
            news.setDuanziDetail(detail);
        }
    }

    @Override
    public void callOnBack(Object object) {
        refresh.onRefreshComplete();
        if (object != null && object instanceof JSONObject) {
            JSONObject result = (JSONObject) object;

            try {

                int status = result.getInt("status");
                if (status == 1) {
                    //////////解析出返回数据的stime，sequence
                    Duanzi duanzi = new Duanzi();
                    duanzi.parseJSON(result);
                    List<Duanzi> newsList = duanzi.getList();

                    for (int i = 0; i < newsList.size(); i++) {
                        //TODO 继续开线程下载详情
                        Duanzi item = newsList.get(i);
                        // 继续开线程下载详情
                        String nid = item.getNid() + "";
                        String url = Constants.DUANZI_DETAIL_URL + nid;
                        DuanziDetailTask task = new DuanziDetailTask(this);
                        task.execute(url, i + "");
                    }
                    data.addAll(0, newsList);
                    adapter.notifyDataSetChanged();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            //TODO 请检查网络
            Toast.makeText(getActivity(), "请检查网络", Toast.LENGTH_SHORT).show();
        }
    }
}
